<template>
    <div class="logincont">
        <div class="kuai">
            <div class="lofinChunk">
                <!-- 公共标题 -->
                <div class="title">
                    <img src="@/assets/images/logo2.png" alt="" width="150px" height="50px">
                </div>
                <div class="topchange">
                    <div :class="{ 'active': isAccount }" @click="isAccount = true">account login</div>
                    <div :class="{ 'active': !isAccount }" @click="isAccount = false">mail login</div>
                </div>
                <div class="form-container">
                    <!-- 账号登录表单 -->
                    <el-form v-if="isAccount" ref="accountFormRef" :model="accountForm" :rules="accountRules"
                        class="login-form">
                        <el-form-item prop="username">
                            <el-input v-model="accountForm.username" type="text" maxlength="16" minlength="8"
                                placeholder="accountnumber">
                                <!-- <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" /> -->
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model="accountForm.password" type="password" maxlength="16" minlength="8"
                                auto-complete="off" placeholder="password">
                                <!-- @keyup.enter.native="handleLogin" -->
                                <!-- <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" /> -->
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input v-model="accountForm.code" auto-complete="off" placeholder="Captcha" maxlength="6"
                                style="width: 63%" @keyup.enter="handleLogin">
                                <!-- <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" /> -->
                            </el-input>
                            <div class="login-code">
                                <img :src="codeUrl" class="login-code-img" @click.native.prevent="codechange" />
                            </div>
                        </el-form-item>
                        <!-- <el-checkbox v-model="accountForm.rememberMe" style="margin:0px 0px 25px 0px;">remember
                    password</el-checkbox> -->
                        <el-form-item style="width:100%;">
                            <el-button :loading="loading" size="default" type="primary"
                                style="width:100%; background-color: #4f40ff;" @click.native.prevent="handleLogin">
                                <span v-if="!loading">login</span>
                                <span v-else>Logging in</span>
                            </el-button>
                            <!-- <div style="float: right;" v-if="register">
                        <router-link class="link-type" :to="'/register'">立即注册</router-link>
                    </div> -->
                        </el-form-item>
                    </el-form>

                    <!-- 邮箱登录表单 -->
                    <el-form v-else ref="emailFormRef" :model="emailForm" :rules="emailRules" class="login-form">
                        <el-form-item prop="email">
                            <el-input v-model="emailForm.email" type="text" placeholder="email" style="width: 80%"
                                maxlength="20" minlength="3">
                                <!-- <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" /> -->
                            </el-input>
                            <el-button style="width: 20%;height: 38px;font-size: 10px;white-space: pre-line;"
                                @click.native.prevent="handleemail" :disabled="isDisable">{{ sendemailfont
                                }}</el-button>
                        </el-form-item>
                        <el-form-item prop="emailCaptcha">
                            <el-input v-model="emailForm.emailCaptcha" type="password" auto-complete="off"
                                placeholder="Email verification code" maxlength="6" @keyup.enter="handleLogin">
                                <!-- @keyup.enter.native="handleLogin" -->
                                <!-- <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" /> -->
                            </el-input>
                        </el-form-item>
                        <!-- <el-checkbox v-model="emailForm.rememberMe" style="margin:0px 0px 25px 0px;">remember
                    password</el-checkbox> -->
                        <el-form-item style="width:100%;">
                            <el-button :loading="loading" size="default" type="primary"
                                style="width:100%; background-color: #4f40ff;" @click.native.prevent="handleLogin">
                                <span v-if="!loading">login</span>
                                <span v-else>Logging in</span>
                            </el-button>
                            <!-- <div style="float: right;" v-if="register">
                        <router-link class="link-type" :to="'/register'">立即注册</router-link>
                    </div> -->
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
// import obj from "../untils/passjs/pad-zeropadding"
import { Encrypt, Decrypt } from "../untils/passjs/security.js"
import { onMounted, reactive, ref } from 'vue';
import { getEmailCode, getCaptchaCode, getLogin, getUserBasicData, getMoveRouter } from "../api/api.js"
// import router from "../router/index copy.js";
// import  router from "../router/index.js";


import { ElMessage } from "element-plus";
import store from "../store/index.js";
import { generatorRoutes } from "../api/generatorRoutes.js";
import { useRouter } from "vue-router";
let routerr = useRouter()
let sendemailfont = ref("Send\nverification code")

// 分开账号和邮箱的登录数据
// 账号+密码
const accountForm = reactive({
    username: '',
    password: '',
    rememberMe: false,
    code: ""
})
// 邮箱+邮箱验证码
const emailForm = reactive({
    email: '',
    emailCaptcha: '',
    rememberMe: false
})
// 账号登录验证规则
const accountRules = ref({
    username: [
        {
            required: true,
            message: 'Please enter your account',
            trigger: 'blur'
        },
        {
            pattern: /^[a-zA-Z0-9]{8,16}$/,
            message: 'The account requires a combination of 8-16 letters or numbers',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            pattern: /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/,
            message: 'Password must contain letters, numbers, and special characters',
            trigger: 'blur'
        }
    ],
    code: [
        {
            required: true,
            message: 'Please enter the verification code',
            trigger: 'blur'
        }
    ]
})
// 邮箱登录验证规则
const emailRules = ref({
    email: [
        { required: true, trigger: "blur", message: "Please enter the correct email address", type: 'email' },
        {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/,
            message: 'Please enter the correct email format',
            trigger: "blur"
        }
    ],
    emailCaptcha: [
        { required: true, trigger: "blur", message: "Please enter the email verification code" }
    ]
})

onMounted(async () => {
    getcodeUrl()
})

let loading = ref(false)
// 账号密码和邮箱的切换isAccount是否是账户密码登录
let isAccount = ref(true)

let captchaId = ref("")
let codeUrl = ref("")

const handleLogin = async () => {

    let usernamerule = /^[a-zA-Z0-9]{8,16}$/
    // let passwordrule = /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,16}$/
    // let passwordrule1 = /^[a-zA-Z]$/;
    // let passwordrule2 = /^[0-9]$/;
    // let passwordrule3 = /[!@#$%^&*()|?.+-/~]/;
    try {
        sessionStorage.setItem('hasInitialized', 'false');
        loading.value = true
        let val;
        if (isAccount.value) {
            var bool = true;
            if (accountForm.username == "" || accountForm.password == "" || accountForm.code == "") {

                bool = false;
            }
            if (bool && (accountForm.password.length > 16 || accountForm.password.length < 8)) {
                getcodeUrl()
                bool = false;
            }
            if (bool && !usernamerule.test(accountForm.username)) {
                getcodeUrl()
                bool = false;
            }
            if (!bool) {
                ElMessage.error("account or password does not meet the requirements")
                return;
            }
            console.log(accountForm, "账号秘密登录数据");
            val = {
                "username": accountForm.username,
                "password": accountForm.password,
                "loginFormat": "0@@0@@0",
                "captcha": {
                    "captchaId": captchaId.value,
                    "projectCode": accountForm.code
                }
            }
            console.log(Encrypt(JSON.stringify(val)));
            console.log(Decrypt(Encrypt(JSON.stringify(val))));
            getcodeUrl()
            // 调用登录接口
            try {
                const res = await getLogin(Encrypt(JSON.stringify(val)));
                console.log('获取的数据:', res)
                if (res.code == 200) {
                    console.log(res);
                    localStorage.setItem("token", res.data.token)
                    // localStorage.setItem("role",res.data.role)
                    // 调用 接口获取 当前用户的role 角色
                    getUserBasicData().then(async res => {
                        console.log(res);
                        if (res.code == 200) {
                            localStorage.setItem("userdetail", JSON.stringify(res.data))
                            // getMoveRouter().then(res=>{
                            //     console.log(res,"router");
                            // })
                            getrouter()
                            loading.value = false
                        } else {
                            loading.value = false
                        }

                    })
                } else {
                    loading.value = false
                    // 刷新验证码
                    console.log("错误");

                    getcodeUrl()
                }
            } catch (error) {
                console.log(error);

            }


        } else {
            try {
                if (emailForm.email == '' || emailForm.emailCaptcha == '') {
                    ElMessage.error("email or emailCaptcha does not meet the requirements")
                    return;
                }
                console.log(emailForm, "邮箱验证码登录数据");
                let val = {
                    "username": emailForm.email,
                    "password": emailForm.emailCaptcha,
                    "loginFormat": "2@@0@@0",
                    "captcha": {}
                }
                console.log(val);

                console.log(Encrypt(JSON.stringify(val)), "1111111");
                console.log(Decrypt(Encrypt(JSON.stringify(val))), "212222jiemi");

                // // 调用登录接口
                const res = await getLogin(Encrypt(JSON.stringify(val)));

                console.log('获取的数据:', res)
                if (res.code == 200) {
                    console.log(res);

                    localStorage.setItem("token", res.data.token)
                    // localStorage.setItem("role",res.data.role)
                    // 调用 接口获取 当前用户的role 角色
                    getUserBasicData().then(res => {
                        console.log(res);
                        if (res.code == 200) {
                            localStorage.setItem("userdetail", JSON.stringify(res.data))
                            getrouter()
                         
                            loading.value = false
                        }
                    })
                } else {
                    loading.value = false
                }
            } catch (error) {
                ElMessage.error("Network error, please try again later");  // 显示网络错误提示
            } finally {
                loading.value = false
            }
        }
        accountForm.username = ""
        accountForm.password = ""
        accountForm.code = ""
        emailForm.email = ''
        emailForm.emailCaptcha = ''
        loading.value = !loading.value
        //   try {
        //     loading.value = true
        //     // 1. 表单验证
        //     await loginFormRef.value.validate()
        //     // // 2. 调用登录接口
        //     // await userStore.login(loginForm)
        //     // // 3. 跳转到首页
        //     // router.push('/')
        //     // ElMessage.success('登录成功')
        //   } catch (error) {
        //     console.error('登录失败:', error)
        //   } finally {
        //     loading.value = false
        //   }
    } catch {
        // ElMessage.error("网络错误，请稍后重试");  // 显示网络错误提示

    } finally {
        loading.value = false
    }
}
const loginFormRef = ref(null)
async function getcodeUrl() {
    try {
        const res = await getCaptchaCode();
        console.log('获取的数据:', res)
        if (res.code == 200) {
            captchaId.value = res.data.captchaId
            codeUrl.value = "data:image/jpeg;base64," + res.data.originalImageBase64
        }
    } catch (error) {
        console.error('请求失败:', error)
    }
}
function codechange() {
    getcodeUrl()
}
async function getrouter() {
    try {
        let ress = await getMoveRouter()
        console.log(ress, "router");
        if (ress.code == 200 && ress.data.length > 0) {
            // ress.data   
            store.commit('addRoutersData', ress.data)
            // data.routesData存到localstroage中
            localStorage.setItem("routesData", JSON.stringify(ress.data))
            console.log(store.state)
            generatorRoutes(ress.data);

            ElMessage({
                message: 'Login succeeded',
                type: 'success',
            })
            routerr.push("/")


        } else {
            ElMessage({
                message: 'No permission to view temporarily',
                type: 'error',
            })
            routerr.push("/nop")
            window.location.reload()
        }
    } catch (error) {
        console.log(error);

    }
}
// function getCode() {
//     getCodeImg().then(res => {
//         this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
//         if (this.captchaEnabled) {
//             this.codeUrl = "data:image/gif;base64," + res.img
//             this.loginForm.uuid = res.uuid
//         }
//     })
// }
// function getCookie() {
//     const username = Cookies.get("username")
//     const password = Cookies.get("password")
//     const rememberMe = Cookies.get('rememberMe')
//     this.loginForm = {
//         username: username === undefined ? this.loginForm.username : username,
//         password: password === undefined ? this.loginForm.password : decrypt(password),
//         rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
//     }
// }
// 点击发送验证码按钮
let isDisable = ref(false)
let num = ref(10)
let timer = ref(null)
async function handleemail() {
    console.log(emailForm.email);
    if (emailForm.email == '') {
        ElMessage.warning("Please enter your email address")
        return;
    }
    isDisable.value = true
    num.value = 10;
    sendemailfont.value = num.value + "s"

    // let num = 10;
    // const timer = setInterval(() => {
    //     num--;
    //     sendemailfont.value = num + "s"
    //     if (num < 1) {
    //         clearInterval(timer);
    //         sendemailfont.value = "Send\nverification code"
    //     }
    // }, 1000);
    try {
        const res = await getEmailCode(emailForm.email)  // 传入GET参数
        console.log('获取的数据:', res.data, "发送验证码")
        if (res.code == 200) {
            console.log("200");
            ElMessage.success(res.msg)
            timer.value = setInterval(() => {
                num.value--;
                if (num.value > 0) {
                    sendemailfont.value = num.value + "s"
                } else {
                    clearInterval(timer.value);
                    sendemailfont.value = "Send\nverification code";
                    isDisable.value = false;
                    timer.value = null;
                }
            }, 1000);
        } else {
            console.log('500');
            clearInterval(timer.value);
            sendemailfont.value = "Send\nverification code";
            isDisable.value = false;
            timer.value = null;
            // ElMessage.error(res.msg)
        }

    } catch (error) {
        emailForm.email = ''
        clearInterval(timer.value);
        sendemailfont.value = "Send\nverification code";
        isDisable.value = false;
        timer.value = null;
    }


}
</script>
<style lang="scss" scoped>
.logincont {
    width: 100vw;
    height: 100vh;
    background: url("../assets/images/bj2.png") no-repeat center center;
    background-size: cover;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .kuai {
        width: 30%;
        background-color: #fff;
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .lofinChunk {
        width: 450px;
        height: 300px;
        position: relative;
        border-radius: 20px;
    }

    /* 登录表单容器 */
    .form-container {
        width: 90%;
        max-width: 450px;

        .login-form {
            width: 100%;
        }
    }

    .title {
        // margin: 0px auto 30px auto;
        text-align: center;
        color: #707070;
    }

    .topchange {
        display: flex;
        justify-content: center;
        gap: 30px;
        margin: 15px 0 10px;

        div {
            cursor: pointer;
            color: #999;
            font-size: 14px;
            position: relative;
            padding-bottom: 5px;
            transition: all 0.3s;

            &.active {
                color: #4f40ff;
                font-weight: bold;

                &::after {
                    content: "";
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    width: 100%;
                    height: 2px;
                    background: #4f40ff;
                }
            }

            &:hover {
                color: #4f40ff;
            }
        }
    }

    .login-form {
        border-radius: 6px;
        // background-color: #b4d6ee;
        background-color: transparent;
        width: 400px;
        padding: 25px 25px 5px 25px;
        z-index: 1;

        .el-input {
            height: 38px;

            input {
                height: 38px;
            }
        }

        .input-icon {
            height: 39px;
            width: 14px;
            margin-left: 2px;
        }
    }

    .login-tip {
        font-size: 13px;
        text-align: center;
        color: #bfbfbf;
    }

    .login-code {
        width: 33%;
        height: 38px;
        float: right;

        img {
            cursor: pointer;
            vertical-align: middle;
        }
    }

    .el-login-footer {
        height: 40px;
        line-height: 40px;
        position: fixed;
        bottom: 0;
        width: 100%;
        text-align: center;
        color: #fff;
        font-family: Arial;
        font-size: 12px;
        letter-spacing: 1px;
    }

    .login-code-img {
        width: 80%;
        height: 38px;
        text-align: end;
        margin-left: 30px;
    }
}
</style>